package com.xiaodou.mjf.application.core.manager;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.xiaodou.mjf.application.basic.utils.SequenceGenerator;
import com.xiaodou.mjf.application.core.service.AccountService;
import com.xiaodou.mjf.application.core.service.NotesBookService;
import com.xiaodou.mjf.application.core.service.OrderSettlementService;
import com.xiaodou.mjf.application.core.service.OrderStatementService;
import com.xiaodou.mjf.application.core.service.WithdrawalRecordService;
import com.xiaodou.mjf.application.core.service.WithdrawalService;
import com.xiaodou.mjf.application.fee.manager.FeeManager;
import com.xiaodou.mjf.application.user.service.MemberService;
import com.xiaodou.mjf.entity.core.Account;
import com.xiaodou.mjf.entity.core.NotesBook;
import com.xiaodou.mjf.entity.core.OrderSettlement;
import com.xiaodou.mjf.entity.core.OrderStatement;
import com.xiaodou.mjf.entity.core.Withdrawal;
import com.xiaodou.mjf.entity.core.WithdrawalRecord;
import com.xiaodou.mjf.entity.user.Member;
import com.xiaodou.mjf.infrastructure.common.app.CommonManager;
import com.xiaodou.mjf.infrastructure.common.components.Result;
import com.xiaodou.mjf.infrastructure.common.context.SpringContextHolder;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.payeco.PayUtils;

/**
 * Created by BILLY on 2015/4/23.
 */

@Component
@Transactional
public class OrderManager extends CommonManager {

	private static Logger logger = Logger.getLogger(FeeManager.class.getName());
	private static OrderStatementService orderStatementService = SpringContextHolder.getBean(OrderStatementService.class);
	private static OrderSettlementService orderSettlementService = SpringContextHolder.getBean(OrderSettlementService.class);
	private static MemberService memberService = SpringContextHolder.getBean(MemberService.class);
	private static WithdrawalRecordService withdrawalRecordService = SpringContextHolder.getBean(WithdrawalRecordService.class);
	private static WithdrawalService withdrawalService = SpringContextHolder.getBean(WithdrawalService.class);
	private static AccountService accountService = SpringContextHolder.getBean(AccountService.class);
	private static NotesBookService notesBookService = SpringContextHolder.getBean(NotesBookService.class);

	/**
	 * 订单结算
	 * 
	 * @param orderIds
	 * @param amount
	 * @return
	 * @throws Exception
	 */
	public Result orderSettlement(String orderIds, Double amount, Integer year, Integer stage, Date settlementDate) throws Exception {
		Result result = new Result();
		try {
			if (orderIds.length() > 0) {
				String[] ids = orderIds.split(",");
				for (String id : ids) {
					OrderStatement orderStatement = orderStatementService.get(id);
					orderStatement.setStatementStatus(OrderStatement.NORMAL);
					orderStatementService.save(orderStatement);
				}
				OrderSettlement orderSettlement = new OrderSettlement();
				orderSettlement.setAmount(amount);
				orderSettlement.setYear(year);
				orderSettlement.setStage(stage);
				orderSettlement.setSettlementDate(settlementDate);
				orderSettlement.setOrderStatementIds(orderIds);
				orderSettlementService.save(orderSettlement);

			}

		} catch (Exception ex) {
			result.setSuccess(false);
			result.setMessage("结算失败:" + ex.toString());
			logger.error(ex.toString());
			throw ex;
		}
		result.setSuccess(true);
		result.setMessage("结算成功");
		return result;

	}

	/**
	 * 提现订单审核
	 * 
	 * @param withdrawalRecord
	 * @return
	 * @throws Exception
	 */
	public Result audit(Withdrawal withdrawal) throws Exception {
		Result result = new Result();
		try {
			Member member = memberService.get(withdrawal.getMemberId());
			//
			Date currDate = DateUtils.getCurrentTime();
			withdrawal.setAuditDate(currDate);
			withdrawalService.save(withdrawal);
			//
			if (withdrawal.getStatus().equals(Withdrawal.NORMAL)) {
				WithdrawalRecord withdrawalRecord = new WithdrawalRecord();
				withdrawalRecord.setSerialNumber(withdrawal.getSerialNumber());
				withdrawalRecord.setRealName(member.getRealName());
				withdrawalRecord.setAccountId(withdrawal.getAccountId());
				withdrawalRecord.setCardNumbert(withdrawal.getCardNumbert());
				withdrawalRecord.setAccountTitle(withdrawal.getAccountTitle());
				withdrawalRecord.setTranChannelId(withdrawal.getTranChannelId());
				withdrawalRecord.setTranChannelResponse(withdrawal.getTranChannelResponse());
				withdrawalRecord.setAmount(withdrawal.getAmount());
				withdrawalRecord.setPorcStatus(WithdrawalRecord.PAY_FAIL.toString());
				withdrawalRecord.setApplyDate(currDate);

				// 支付
				PayUtils.pay(withdrawal.getSerialNumber(), withdrawal.getCardNumbert(), withdrawal.getAccountTitle(), withdrawal.getAmount(), "", "0", withdrawal.getId());

			}

		} catch (Exception ex) {
			result.setSuccess(false);
			result.setMessage("审核失败");
		}
		result.setSuccess(true);
		result.setMessage("审核成功");
		return result;

	}

	/**
	 * 获取已审核未支付成功的提现订单
	 */
	public void getOrderUnPayment() throws Exception {

		try {
			List<WithdrawalRecord> withdrawalRecords = withdrawalRecordService.getOrderUnPayment();
			List<WithdrawalRecord> entities = Lists.newArrayList();
			if (withdrawalRecords.size() > 0) {
				for (WithdrawalRecord entity : withdrawalRecords) {

					if (PayUtils.payQuery(entity.getSerialNumber(), entity.getId())) {
						entity.setProcDate(DateUtils.getCurrentTime());
						entity.setPorcStatus(WithdrawalRecord.PAY_SUECCESS.toString());
						entities.add(entity);

						//
						Account account = accountService.get(entity.getAccountId());
						Date currentTime = DateUtils.getCurrentTime();
						NotesBook notesBook = new NotesBook();
						notesBook.setType(NotesBook.TYPE_WITHDRAWAL);
						notesBook.setAccount(account.getNumber());
						notesBook.setAdditionalText("提现");
						notesBook.setBalance(account.getPreviousBalance());
						notesBook.setAmount(entity.getAmount());
						notesBook.setProcDate(currentTime);
						notesBook.setDescription("提现");
						notesBook.setDrcr(NotesBook.CR);
						notesBook.setSerialNumber(SequenceGenerator.generateNotesBook(SequenceGenerator.TYPE_NOTEBOOK, entity.getTranChannelId()));
						notesBook.setTxnDate(currentTime);
						notesBookService.save(notesBook);
					}
				}
			}

			withdrawalRecordService.save(entities);

		} catch (Exception ex) {
			logger.error(ex);
			throw ex;
		}
	}

}
